{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 96,
   "id": "fd0b1a92",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from datetime import datetime, timedelta\n",
    "import simfin as sf\n",
    "from simfin.names import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "id": "aa959ae6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Set the SimFin data-directory\n",
    "sf.set_data_dir(\"C:\\\\dev\\\\trading\\\\tradesystem1\\\\data\\\\simfin\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "id": "00f124d8",
   "metadata": {},
   "outputs": [],
   "source": [
    "#  Set your API Key\n",
    "sf_api_key = \"<your API key>\"\n",
    "sf.set_api_key(sf_api_key)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "id": "da364502",
   "metadata": {},
   "outputs": [],
   "source": [
    "#  Configure SimFin hub with cache refresh params\n",
    "variant = 'latest' #  latest or ttm\n",
    "hub = sf.StockHub(market='us',\n",
    "                  refresh_days=30,\n",
    "                  refresh_days_shareprices=1)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 100,
   "id": "1bf297b0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dataset \"us-income-quarterly\" on disk (0 days old).\n",
      "- Loading from disk ... Done!\n",
      "Ticker\n",
      "Report Date\n",
      "SimFinId\n",
      "Currency\n",
      "Fiscal Year\n",
      "Fiscal Period\n",
      "Publish Date\n",
      "Restated Date\n",
      "Shares (Basic)\n",
      "Shares (Diluted)\n",
      "Revenue\n",
      "Cost of Revenue\n",
      "Gross Profit\n",
      "Operating Expenses\n",
      "Selling, General & Administrative\n",
      "Research & Development\n",
      "Depreciation & Amortization\n",
      "Operating Income (Loss)\n",
      "Non-Operating Income (Loss)\n",
      "Interest Expense, Net\n",
      "Pretax Income (Loss), Adj.\n",
      "Abnormal Gains (Losses)\n",
      "Pretax Income (Loss)\n",
      "Income Tax (Expense) Benefit, Net\n",
      "Income (Loss) from Continuing Operations\n",
      "Net Extraordinary Gains (Losses)\n",
      "Net Income\n",
      "Net Income (Common)\n",
      "   Ticker  INCOME_GROWTH_MA4\n",
      "0     ADI           0.202279\n",
      "1      AI           0.298943\n",
      "2    AMBA           1.925286\n",
      "3   AMSWA           0.422999\n",
      "4    ASPU           0.305638\n",
      "..    ...                ...\n",
      "59   VALU           0.332183\n",
      "60  VLGEA           0.737297\n",
      "61    VMW           1.364544\n",
      "62   VSCO           6.001084\n",
      "63   WEWA           0.264045\n",
      "\n",
      "[64 rows x 2 columns]\n"
     ]
    }
   ],
   "source": [
    "#  Load quartely income in line line!!!\n",
    "income_df = hub.load_income(variant='quarterly')  # annual or quarterly\n",
    "income_df = income_df.reset_index()\n",
    "for col in income_df.columns:\n",
    "    print(col)\n",
    "income_df['INCOME_GROWTH'] = income_df[OPERATING_INCOME].pct_change(periods=1)\n",
    "#  Average income growth in the last 4 quarters\n",
    "income_df['INCOME_GROWTH_MA4'] = income_df['INCOME_GROWTH'].rolling(4).mean()\n",
    "#  Gross income growth last 4 quarters\n",
    "income_mask = income_df['INCOME_GROWTH_MA4'] > 0.20\n",
    "\n",
    "#  Calculate past 3 months\n",
    "today = datetime.today()\n",
    "today_date_str = today.strftime(\"%Y-%m-%d\")\n",
    "past_date = today - timedelta(days=90)\n",
    "past_date_str = past_date.strftime(\"%Y-%m-%d\")\n",
    "\n",
    "#  Get last 3 months of reporting\n",
    "income_mask &= ((income_df[REPORT_DATE] >= past_date_str) & (income_df[REPORT_DATE] <= today_date_str))\n",
    "\n",
    "#  Format results\n",
    "income_results = income_df[income_mask]\n",
    "income_results = income_results.groupby(['Ticker']).mean()\n",
    "income_results.reset_index(inplace=True)\n",
    "income_results = income_results[['Ticker', 'INCOME_GROWTH_MA4']]\n",
    "print(income_results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "id": "680f0a50",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dataset \"us-derived-quarterly\" on disk (0 days old).\n",
      "- Loading from disk ... Done!\n",
      "Ticker\n",
      "Report Date\n",
      "SimFinId\n",
      "Currency\n",
      "Fiscal Year\n",
      "Fiscal Period\n",
      "Publish Date\n",
      "Restated Date\n",
      "EBITDA\n",
      "Total Debt\n",
      "Free Cash Flow\n",
      "Gross Profit Margin\n",
      "Operating Margin\n",
      "Net Profit Margin\n",
      "Return on Equity\n",
      "Return on Assets\n",
      "Free Cash Flow to Net Income\n",
      "Current Ratio\n",
      "Liabilities to Equity Ratio\n",
      "Debt Ratio\n",
      "Earnings Per Share, Basic\n",
      "Earnings Per Share, Diluted\n",
      "Sales Per Share\n",
      "Equity Per Share\n",
      "Free Cash Flow Per Share\n",
      "Dividends Per Share\n",
      "Piotroski F-Score\n",
      "Return On Invested Capital\n",
      "Cash Return On Invested Capital\n",
      "Dividend Payout Ratio\n",
      "Net Debt / EBITDA\n",
      "Net Debt / EBIT\n",
      "      Ticker\n",
      "10527    BKE\n",
      "17860   CODA\n",
      "18806   CPRT\n",
      "28445   FAST\n",
      "34697    HEI\n",
      "44827   LOVE\n",
      "49643    MOV\n",
      "50851     MU\n",
      "68159    SLP\n",
      "68624   SMTC\n",
      "71434   SWBI\n",
      "78023   VALU\n",
      "78305   VEEV\n",
      "84041   ZDGE\n",
      "84222     ZM\n"
     ]
    }
   ],
   "source": [
    "#  Get financial ratios\n",
    "financial_ratios_df = hub.load_derived(variant='quarterly')  # annual or quarterly\n",
    "financial_ratios_df = financial_ratios_df.reset_index()\n",
    "for col in financial_ratios_df.columns:\n",
    "    print(col)\n",
    "\n",
    "\n",
    "#  Build the mask\n",
    "#  Company’s current assets to its current liabilities.\n",
    "financial_mask = (financial_ratios_df[CURRENT_RATIO] > 1.5)\n",
    "# The debt ratio is defined as the ratio of total debt to total assets\n",
    "financial_mask &= (financial_ratios_df[DEBT_RATIO] < 0.2)\n",
    "financial_mask &= (financial_ratios_df[NET_PROFIT_MARGIN] > 0.15)\n",
    "#  Get last 3 months of reporting\n",
    "financial_mask &= ((financial_ratios_df[REPORT_DATE] >= past_date_str) & (financial_ratios_df[REPORT_DATE] <= today_date_str))\n",
    "\n",
    "financial_selections_df = financial_ratios_df[financial_mask]\n",
    "financial_results = financial_selections_df[['Ticker']]\n",
    "print(financial_results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 104,
   "id": "1ed37897",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Ticker\n",
      "Date\n",
      "SimFinId\n",
      "Market-Cap\n",
      "Price to Earnings Ratio (quarterly)\n",
      "Price to Earnings Ratio (ttm)\n",
      "Price to Sales Ratio (quarterly)\n",
      "Price to Sales Ratio (ttm)\n",
      "Price to Book Value\n",
      "Price to Free Cash Flow (quarterly)\n",
      "Price to Free Cash Flow (ttm)\n",
      "Enterprise Value\n",
      "EV/EBITDA\n",
      "EV/Sales\n",
      "EV/FCF\n",
      "Book to Market Value\n",
      "Operating Income/EV\n",
      "Altman Z Score\n",
      "      Ticker\n",
      "10527    BKE\n",
      "17860   CODA\n",
      "18806   CPRT\n",
      "28445   FAST\n",
      "34697    HEI\n",
      "44827   LOVE\n",
      "49643    MOV\n",
      "50851     MU\n",
      "68159    SLP\n",
      "68624   SMTC\n",
      "71434   SWBI\n",
      "78023   VALU\n",
      "78305   VEEV\n",
      "84041   ZDGE\n",
      "84222     ZM\n"
     ]
    }
   ],
   "source": [
    "#  Price Ratio Screening\n",
    "price_ratio_df = hub.load_derived_shareprices(variant='daily')  # daily or latest\n",
    "price_ratio_df = price_ratio_df.reset_index()\n",
    "for col in price_ratio_df.columns:\n",
    "    print(col)\n",
    "\n",
    "#  Build the mask\n",
    "# The price-to-earnings ratio (P/E ratio) is the  current share price relative to its earnings per share (EPS)\n",
    "price_ratio_mask = (price_ratio_df[PE_QUARTERLY] < 25)\n",
    "#  The price-to-cash flow (P/CF) ratio compares a company's market value to its operating cash flow or\n",
    "#  its stock price per share to operating cash flow per share\n",
    "price_ratio_mask &= (price_ratio_df[PRICE_FCF_QUARTERLY] < 20)\n",
    "#  Get last 3 months of reporting\n",
    "price_ratio_mask &= ((price_ratio_df['Date'] >= past_date_str) & (price_ratio_df['Date'] <= today_date_str))\n",
    "\n",
    "price_selections_df = price_ratio_df[price_ratio_mask]\n",
    "price_results = price_selections_df.groupby(['Ticker']).mean()\n",
    "price_results.reset_index(inplace=True)\n",
    "price_results = financial_selections_df[['Ticker']]\n",
    "print(price_results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ec75100d",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda env:tradesystem1]",
   "language": "python",
   "name": "conda-env-tradesystem1-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
